package manager

import ext.log
import mvc.model.HeatData
import org.json.JSONArray
import protocol.BaseProtocol
import serialport.DeliverPortManager

object HeatManager : Runnable {

    var HeatDataInfos = emptyArray<HeatData>()

    private val controlTask = HeatControlTask()

    override fun run() {
        try {
            val result = HttpRequestManager.refreshControlHeatData()
            log("---$result", "温度控制数据")
            val arr = JSONArray(result)
            val len = arr.length()
            HeatDataInfos = Array(len) { HeatData.withJson(arr.getJSONObject(it)) }
            TaskManager.DelayHandler.removeCallbacks(controlTask)
            TaskManager.DelayHandler.post(controlTask)
        } catch (e: Exception) {
            e.printStackTrace()
            TaskManager.DelayHandler.postDelayed(this, 60 * 1000)
        }
    }

    fun refreshAsync() {
        TaskManager.DelayHandler.post(this)
    }

    private fun control() {
        for (info in HeatDataInfos) {
            if (info.isExist()) {
                log(info.toString(), "开始温度控制")
                val buf = BaseProtocol(0x11)
                    .appendByte(info.maxTempValue + 20)
                    .appendByte(info.minTempValue + 20)
                    .build()
                DeliverPortManager.Instance.write(buf)
                return
            }
        }
        val buf = BaseProtocol(0x11)
            .appendByte(100)
            .appendByte(0)
            .build()
        DeliverPortManager.Instance.write(buf)
        if (HeatDataInfos.isEmpty()) {
            log("没有温度数据", "温度控制")
        } else {
            log("温度设置不在本时间段", "温度控制")
        }
    }

    private class HeatControlTask : Runnable {
        override fun run() {
            try {
                HeatManager.control()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            TaskManager.DelayHandler.postDelayed(this, 60 * 1000)
        }
    }

}


